import { getSession } from '@/lib/auth';
import redis, { genCartKey } from '@/lib/redis';
import { result } from '@/lib/utils';
import { BizError, ErrorCode } from '../error';

export const getCart = async (shopId: number) => {
  try {
    const session = await getSession();
    if (!session?.user)
      throw new BizError(ErrorCode.Unauthorized, '用户未登录');
    const cartJSON = await redis.get(genCartKey(session.user.id, shopId));
    const cart = JSON.parse(cartJSON || '{}') as Record<string, number>;
    return result(cart);
  } catch (error) {
    return result(error, '获取购物车失败');
  }
};
